﻿using System.Runtime.InteropServices;
using System.Text.Json;
using BLL.DTO.RoleDto;
using BLL.Manager;
using Helper;
using HZY.Framework.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using MiniExcelLibs;
using Model.EntityInfo;
using Sunny.UI;
using WinFormsSprayProcessSCADASystem.Extension;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace WinFormsSprayProcessSCADASystem.Pages
{
    public partial class PageWebView : UIPage, IScopedSelfDependency
    {
        private readonly UserManager _userManager;
        private readonly RoleManager _roleManager;
        private readonly RouteManager _routeManager;
        public PageWebView(UserManager userManager, RoleManager roleManager, RouteManager routeManager)
        {
            InitializeComponent();
            this._userManager = userManager;
            this._roleManager = roleManager;
            _routeManager = routeManager;
            InitWebViewEvent();
        }

        private async void InitWebViewEvent()
        {
            await webView21.EnsureCoreWebView2Async(); // 确保 WebView2 初始化完成
                                                       // 配置主机对象访问策略
            var settings = webView21.CoreWebView2.Settings;
            settings.AreDefaultContextMenusEnabled = true;
#if DEBUG
            settings.AreDevToolsEnabled = true; // 调试时启用
#endif
            settings.IsScriptEnabled = true;
            settings.AreHostObjectsAllowed = true;

            Globals.ServiceProvider.GetRequiredService<MainForm>().ThemeCahnge += ChangeTheme;

            // 监听主文档导航完成事件（更适合注册 dotNetBridge）
            webView21.CoreWebView2.NavigationCompleted += (s, e) =>
            {
                if (e.IsSuccess)
                {
                    RegisterDotNetBridge();
                }
            };

        }

        private void RegisterDotNetBridge()
        {
            try
            {
                webView21.CoreWebView2.AddHostObjectToScript("dotNetBridge", new BridgeObject.DotNetBridge(_roleManager, _routeManager));
                webView21.CoreWebView2.AddHostObjectToScript("recipeBridge", Globals.ServiceProvider.GetRequiredService<PageRecipeManage>());
                webView21.CoreWebView2.AddHostObjectToScript("logBridge", Globals.ServiceProvider.GetRequiredService<PageLogManage>());
                webView21.CoreWebView2.AddHostObjectToScript("dataLogBridge", Globals.ServiceProvider.GetRequiredService<PageReportManage>());

                // 注册后立即测试（通过执行 JavaScript 代码）
                webView21.CoreWebView2.ExecuteScriptAsync(
                    "console.log('DotNetBridge 已注册'); " +
                    "window.isInitOk = true;" +
                    "window.dotNetBridge = window.chrome.webview.hostObjects.dotNetBridge;" +
                    "window.recipeBridge = window.chrome.webview.hostObjects.recipeBridge;" +
                    "window.logBridge = window.chrome.webview.hostObjects.logBridge;" +
                    "window.dataLogBridge = window.chrome.webview.hostObjects.dataLogBridge;"
                );

            }
            catch (Exception ex)
            {
                Console.WriteLine($"注册失败: {ex.Message}");
            }
        }

        public void SwitchPage(string url)
        {
            bool isSourceSet = webView21.Source != null && webView21.Source.AbsoluteUri != "about:blank";
            if (!isSourceSet)
            {
                try
                {
                    //webView21.Source = new Uri("http://localhost:5173" + url.Replace("/", "#"), true);
                    webView21.Source = new Uri("D:\\code\\myCode\\study\\CSharp\\WinFormsSprayProcessSCADASystem\\code\\WinFormsSprayProcessSCADASystem\\WWWRoot\\dist\\index.html#" + url.Replace("/", ""), true);
                    //webView21.Source = new Uri("http://127.0.0.1:25378" + url);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    this.LogError(ex.Message);
                }
            }
            else
            {

                webView21.CoreWebView2.ExecuteScriptAsync(
                    $"window.router.push('{url}');" // 直接调用 Vue Router API
                );

            }
        }

        public void ChangeTheme(string colorType)
        {
            webView21.CoreWebView2.ExecuteScriptAsync(
                $"window.changeTheme('{colorType}');" // 直接调用 Vue Router API
            );
        }

    }
}


[ComVisible(true)]
public class BridgeObject
{
    [ComVisible(true)]
    public class DotNetBridge
    {
        private readonly RoleManager _roleManager;
        private readonly RouteManager _routeManager;

        // 添加构造函数接收RoleManager
        public DotNetBridge(RoleManager roleManager, RouteManager routeManager)
        {
            _roleManager = roleManager;
            _routeManager = routeManager;
        }
        #region 角色页面
        //获取角色列表
        [ComVisible(true)]
        public async Task<string> GetAllRole()
        {
            BaseResult<List<RoleInfoModel>> res = await _roleManager.GetAllRole();
            string jsonResult = JsonSerializer.Serialize(res, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true  // 可选：美化格式
            });
            return jsonResult;
        }
        //获取路由列表
        [ComVisible(true)]
        public async Task<string> GetAllRoutes()
        {
            var res = await _routeManager.GetAllRoute();
            string jsonResult = JsonSerializer.Serialize(res, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true  // 可选：美化格式
            });
            return jsonResult;
        }

        //新增角色
        [ComVisible(true)]
        public async Task<string> AddRole(string queryStr)
        {
            AddRoleDto data = JsonSerializer.Deserialize<AddRoleDto>(queryStr);
            var res = await _roleManager.AddRoleAsync(data);
            string jsonResult = JsonSerializer.Serialize(res, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true  // 可选：美化格式
            });
            return jsonResult;
        }

        //删除角色
        [ComVisible(true)]
        public async Task<string> DellRole(string queryStr)
        {
            DellRoleDto data = JsonSerializer.Deserialize<DellRoleDto>(queryStr);
            var res = await _roleManager.DellRoleAsync(data);
            string jsonResult = JsonSerializer.Serialize(res, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true  // 可选：美化格式
            });
            return jsonResult;
        }

        //更新角色
        [ComVisible(true)]
        public async Task<string> UpdateRole(string queryStr)
        {
            UpdateRoleDto data = JsonSerializer.Deserialize<UpdateRoleDto>(queryStr);
            var res = await _roleManager.UpdateRoleAsync(data);
            string jsonResult = JsonSerializer.Serialize(res, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true  // 可选：美化格式
            });
            return jsonResult;
        }

        #endregion

        [ComVisible(true)]
        public void ExportExcel(string data, string title = "")
        {
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                // 设置文件对话框属性
                saveFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx|Excel 97-2003 文件 (*.xls)|*.xls";
                saveFileDialog.Title = "请选择保存位置";
                saveFileDialog.DefaultExt = "xlsx";
                saveFileDialog.AddExtension = true;
                saveFileDialog.CheckPathExists = true;
                saveFileDialog.ValidateNames = true;

                // 设置默认文件名（可选）
                saveFileDialog.FileName = String.IsNullOrEmpty(title) ? $"数据导出_{DateTime.Now:yyyyMMdd_HHmmss}" : title;

                // 显示对话框并处理结果
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        List<Dictionary<string, object>> rows = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(data);

                        // 导出数据到 Excel
                        MiniExcel.SaveAs(saveFileDialog.FileName, rows, true, "Sheet1", ExcelType.UNKNOWN, null, true);

                        //// 导出成功提示
                        MessageBox.Show("数据已成功导出到 Excel 文件！", "导出成功",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        // 权限错误处理
                        MessageBox.Show($"无法访问指定位置：{ex.Message}", "权限错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (IOException ex)
                    {
                        // IO 错误处理
                        MessageBox.Show($"文件操作错误：{ex.Message}", "导出失败",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        // 其他错误处理
                        MessageBox.Show($"导出过程中发生错误：{ex.Message}", "错误",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}